from DrissionPage import ChromiumPage
import requests
import os
import time


# 输入链接
url = input('请输入抖音视频链接：')


# 打包
# region
from DrissionPage import Chromium, ChromiumOptions, SessionOptions

co = ChromiumOptions(ini_path=r'.\configs.ini')
so = SessionOptions(ini_path=r'.\configs.ini')
browser = Chromium(addr_or_opts=co, session_options=so)
# endregion



# 函数
# region
# 图片
def down_images(images, mkdir_cont, images_cont):
    # 图片
    if not os.path.exists(f'抖音/{mkdir_cont}/图片'):
        os.mkdir(f'抖音/{mkdir_cont}/图片')
    for image in images:
        image_url = image['url_list'][-1]
        print(f'图片链接：{image_url}')
        print(f'【图片】：{images_cont}.jpeg开始下载中')
        image_content = requests.get(image_url, headers=headers).content
        with open(f'抖音/{mkdir_cont}/图片/{images_cont}.jpeg', 'wb') as f:
            f.write(image_content)
        print(f'【图片】提示：{images_cont}.jpeg，下载完成')
        images_cont += 1







# 封面图
def down_cover(al, mkdir_cont, cont):
    cover = al['video']['cover']['url_list'][0]
    print(f'【封面图】：{cont}.jpeg开始下载中')
    cover_content = requests.get(cover, headers=headers).content
    with open(f'抖音/{mkdir_cont}/封面图/{cont}.jpeg', 'wb') as f:
        f.write(cover_content)
    print(f'【封面图】提示：{cont}.jpeg，下载完成')





# 音乐
def down_music(al, mkdir_cont, cont):
    try:
        music = al['music']['play_url']['url_list'][-1]
        print(f'音乐链接：{music}')
        print(f'【音乐】：{cont}.mp3开始下载中')
        music_content = requests.get(music, headers=headers).content
        with open(f'抖音/{mkdir_cont}/音乐/{cont}.mp3', 'wb') as f:
            f.write(music_content)
        print(f'【音乐】提示：{cont}.mp3，下载完成')
    except:
        print('没有音乐')




# 小视频
def down_videoImage(images, mkdir_cont, video_cont, cont):
    # 创建小视频目录
    if not os.path.exists(f'抖音/{mkdir_cont}/小视频'):
        os.mkdir(f'抖音/{mkdir_cont}/小视频')
    # 下载每个小视频
    for image in images:
        # print(image)
        # 小视频链接
        videoImage = image['video']['play_addr']['url_list'][-1]
        print(f'小视频链接：{videoImage}')
        print(f'【小视频】：{cont}-{video_cont}开始下载中')
        # 请求
        videoImage_content = requests.get(videoImage, headers=headers).content
        # 文件后缀
        sip = videoImage.split('.')[-1]
        # .mp3处理
        if sip == 'mp3':
            if not os.path.exists(f'抖音/{mkdir_cont}/小视频/mp3'):
                os.mkdir(f'抖音/{mkdir_cont}/小视频/mp3')
            with open(f'抖音/{mkdir_cont}/小视频/mp3/{cont}-{video_cont}.{sip}', 'wb') as f:
                f.write(videoImage_content)
        # .mp4处理
        else:
            with open(f'抖音/{mkdir_cont}/小视频/{cont}-{video_cont}.{sip}', 'wb') as f:
                f.write(videoImage_content)
        print(f'【小视频】提示：{cont}-{video_cont}.{sip}，下载完成')
        video_cont += 1





# 视频
def down_video(al, mkdir_cont, cont):
    # 视频链接
    video_url = al['video']['play_addr']['url_list'][-1]
    print(f'视频链接：{video_url}')
    if '.mp3' in video_url:
        # 保存视频音乐
        print(f'【视频音乐】：{cont}.mp3开始下载中')
        # 请求
        video_content_music = requests.get(video_url, headers=headers).content
        # 保存视频
        with open(f'抖音/{mkdir_cont}/视频/{cont}.mp3', 'wb') as f:
            f.write(video_content_music)
        print(f'【视频音乐】提示：{cont}.mp3，保存完成')
    else:
        # 保存
        print(f'【视频】：{cont}.mp4开始下载中')
        # 请求
        video_content = requests.get(video_url, headers=headers).content
        # 保存视频
        with open(f'抖音/{mkdir_cont}/视频/{cont}.mp4', 'wb') as f:
            f.write(video_content)
        print(f'【视频】提示：{cont}.mp4，保存完成')
    return video_url






# 标题
def title(al):
    title = al['desc']
    print(f'【标题】：{title}')
    return title





# id
def awemeId(al):
    aweme_id = al['aweme_id']
    print(f'【aweme_id】：{aweme_id}')
    return aweme_id






# 创建多个子目录
def mkdir(mkdir_cont):
    # 个数
    if not os.path.exists(f'抖音/{mkdir_cont}'):
        os.mkdir(f'抖音/{mkdir_cont}')
    # 视频
    if not os.path.exists(f'抖音/{mkdir_cont}/视频'):
        os.mkdir(f'抖音/{mkdir_cont}/视频')
    # 封面图
    if not os.path.exists(f'抖音/{mkdir_cont}/封面图'):
        os.mkdir(f'抖音/{mkdir_cont}/封面图')
    # 音乐
    if not os.path.exists(f'抖音/{mkdir_cont}/音乐'):
        os.mkdir(f'抖音/{mkdir_cont}/音乐')



# endregion


# 抖音视频主目录
if not os.path.exists('抖音'):
    os.mkdir('抖音')



# 浏览器请求头
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
    'referer': 'https://www.douyin.com/'
}
# 页数
mkdir_cont = 1
dp = ChromiumPage()
# 链接
# 模特
# url = 'https://www.douyin.com/user/MS4wLjABAAAANJUcXIjMaHQkRFY3Y_I3KdIPVDhTe9SRX2qZ0_11Tb7IntI9tD2cf8mzw-Eh6Sx_'
# 羊村懒大王-
# url = 'https://www.douyin.com/user/MS4wLjABAAAAcA5Vf0MkzyDdntBKz82K24mLurDEoVvE2aNXNrQeuQ0?from_tab_name=main'
# 你的小君
# url = 'https://www.douyin.com/user/MS4wLjABAAAABm7QFedOJrk1e9LqWfoe5L25ZhqTShYkfykxOgmeD-c?from_tab_name=main'
# 璐璐有点夹
# url = 'https://www.douyin.com/user/MS4wLjABAAAAcBZ5XbI1arhQJRmEyOiQQx1ewn4wKOrPxR4z2wXkhyE0imevDWn3F1LGMnIfc7rK?from_tab_name=main'
# 冉冉OvO
# url = 'https://www.douyin.com/user/MS4wLjABAAAA9NFb4wvyEni1JGWx39a_mkY0pbcfzXGG4FJXK22lZmk?from_tab_name=main&vid=7491979263969742134'
#

#

#

#



# 监听
dp.listen.start('aweme/post/')
# # 访问
dp.get(url)
while True:
    # 创建文件夹
    mkdir(mkdir_cont)
    # 等待数据
    res = dp.listen.wait()
    # json数据
    json_data = res.response.body
    # print(json_data)
    # 列表
    als = json_data['aweme_list']
    # 计数
    cont = 1
    # 小视频计数
    video_cont = 1
    # 图片计数
    images_cont = 1
    # 循环
    for al in als:
        # print(al)
        print(f'======【{mkdir_cont}-{cont}-开始】======')
        # 标题
        al_title = title(al)
        # 小视频
        print('******【检测小视频】******')
        images = al['images']
        if not images == None:
            b = []
            for i in images:
                if 'video' in i:
                    b.append('true')
            if 'true' in b:
                # print(b)
                print('---------------开始下载小视频-----------------')
                down_videoImage(images, mkdir_cont, video_cont, cont)
        else:
            print('没有小视频')
        print('等待中...')
        time.sleep(5)
        # 图片
        print('******【检测图片】******')
        if not images == None:
            print('######【开始下载图片】######')
            down_images(images, mkdir_cont, images_cont)
        else:
            print('没有图片')
        print('等待中...')
        time.sleep(5)
        # 音乐
        print('$$$$$$【开始下载音乐】$$$$$$')
        down_music(al, mkdir_cont, cont)
        print('等待中...')
        time.sleep(5)
        # 封面图
        print('&&&&&&【开始下载封面图】&&&&&&')
        down_cover(al, mkdir_cont, cont)
        print('等待中...')
        time.sleep(5)
        # id
        awemeid = awemeId(al)
        # 视频
        print('------【开始下载视频】------')
        video_url = down_video(al, mkdir_cont, cont)
        # 标题，id，视频链接
        print(f'{mkdir_cont}-{cont}，标题：{al_title}，id：{awemeid}，视频链接：{video_url}')
        print(f'======【{mkdir_cont}-{cont}-结束】======')
        cont += 1
    mkdir_cont += 1
    # # 滚动到底部
    footer = dp.ele('css:.user-page-footer')
    dp.scroll.to_see(footer)





# while True:
#     footer = dp.ele('css:.user-page-footer')
#     dp.scroll.to_see(footer)


# region
# 视频音乐
# aweme_list[0].video.play_addr.url_list
# https://sf5-hl-ali-cdn-tos.douyinstatic.com/obj/ies-music/7266619798409300773.mp3
# https://www.douyin.com/aweme/v1/play/?video_id=v0300fg10000csjl9p7og65m5fu8an60&line=0&file_id=66d5cfcebb2249bcb42c3adee4e72d99&sign=3e49abb31e3f0579dfe5ff02e1303c34&is_play_url=1&source=PackSourceEnum_PUBLISH
# endregion





#

